package com.vf.cloud.paas.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.jfinal.kit.StrKit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RedisUtil {
	private static String installPath = "E:\\VFCloudPaaS";
	private static int port = 6400;

	public static void main(String[] args) {
		startRedis(installPath, port);
	}
	
	public static void startRedis(String softPath, int port) {
		ProssUtil.killByPort("" + port);
		if (!StrKit.isBlank( ProssUtil.getPid("6400"))) {
			return;
		}
		executeCmd(String.format("%s/Redis/redis-server.exe %s/Redis/redis.windows.conf ", softPath, softPath),
				"start");
		while(true) {
			if (!StrKit.isBlank(ProssUtil.getPid("6400"))) {
				break;
			}
		}
	}

	static boolean executeCmd(String command, String type) {
		boolean isSucc = false;
		try {
			Runtime runtime = Runtime.getRuntime();
			Process process = runtime.exec("cmd /c start /b " + command);
			new Thread(new ConsoleThread(new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"))))
			.start();
			process.waitFor();
		} catch (InterruptedException | IOException e) {
		}
		return isSucc;
	}

	
	static class ConsoleThread implements Runnable {
		private BufferedReader bfr = null;

		public ConsoleThread(BufferedReader bfr) {
			this.bfr = bfr;
		}

		@Override
		public void run() {
			try {
				String line="";
				while ((line = bfr.readLine()) != null) {
					log.info(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
